package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import javax.swing.JFileChooser;
import javax.swing.JFrame;



public class CsvFilesChecker extends JFrame {

	private String[][] csvContentsPreview = new String[10][10];
	
	public CsvFilesChecker()throws Exception
	{
		JFileChooser fileChooser = new JFileChooser("File");
		int option = fileChooser.showOpenDialog(this);
		if(option == JFileChooser.APPROVE_OPTION)
		{
			readFile(fileChooser.getSelectedFile());
		}
	}
	
	private void readFile(File file) throws Exception
	{
		BufferedReader reader = new BufferedReader(new FileReader(file));
		
		String line = "";
		
		int counter_0 = 0;
		int counter_1 = 0;
		int counter_n = 0;
		int counter_other = 0;
		int maximum = 0;
		
		boolean firstTime = true;
		int lineCounter = 0;
		int columnSize = 0;
		int n= 0;
		
		while((line = reader.readLine()) != null)
		{
			String[] lineSplit = line.split(",");
			if(firstTime)
			{
				columnSize = lineSplit.length;
				System.out.println("Column size: " + columnSize);
				firstTime = false;
			}
			
			if(lineCounter % (columnSize / 10) == 0)
			{
				
				System.out.println("Reading line " + lineCounter + " out of " + columnSize + " --- " + n + "%");
				n+=10;
			}
			
			
			for(int i = 0; i <lineSplit.length; i++)
			{
				if(i < 10 && lineCounter < 10)
				{
					csvContentsPreview[lineCounter][i] = lineSplit[i];
				}
				try
				{
					int number = Integer.parseInt(lineSplit[i]);
					switch(number)
					{
					case 0:
						counter_0++;
						break;
					case 1:
						counter_1++;
						break;
					default:
						if(maximum < number)
						{
							maximum = number;
						}
						counter_n++;
					}
				}catch(Exception e)
				{
					counter_other++;
				}
			}
			lineCounter++;
		}
		
		System.out.println("File: " + file.getName());
		System.out.println("Number of 0s    : " + counter_0);
		System.out.println("Number of 1s    : " + counter_1);
		System.out.println("Number of n     : " + counter_n);
		System.out.println("Number of NaN   : " + counter_other);
		System.out.println("Maximum         : " + maximum);
		System.out.println("Lines read      : " + lineCounter);
		
		System.out.println("csv preview");
		for(int i = 0; i < csvContentsPreview.length; i++)
		{
			for(int j = 0; j < csvContentsPreview[0].length; j++)
			{
				System.out.print(csvContentsPreview[i][j] + ",");
			}	
			System.out.print("\n");
		}
		System.exit(0);
	}
	public static void main(String[] args)
	{
		try {
			new CsvFilesChecker();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
